<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    ErrorController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    ErrorController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Storefront_ErrorController extends Zend_Controller_Action
{

    /**
     * Action for error
     * @return void 
     */
    public function errorAction()
    {
        // Check an error type
        $errors = $this->_getParam('error_handler');
        if (!$errors || !$errors instanceof ArrayObject) {
            $this->view->message = 'You have reached the error page';
            return;
        }

        // Log priority
        $priority = null;

        // Analyze an error type
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Page not found';
                break;
            default:

                // Application error
                $this->getResponse()->setHttpResponseCode(500);
                $priority = Zend_Log::CRIT;
                $this->view->message = 'Application error';
                break;
        }

        // Check the logger
        $log = Zend_Registry::get('log');
        if ($log) {
            $message = $this->view->message;

            // Check excpeption
            if (isset($errors->exception)) {

                // Write exeption to log
                if ($this->getInvokeArg('displayExceptions') == true || $priority == Zend_Log::CRIT) {
                    $message .= "\nMessage: ";
                    $message .= $errors->exception->getMessage();
                    $message .= "\nStack trace:\n";
                    $message .= $errors->exception->getTraceAsString();
                    $message .= "\nRequest Parameters:\n";
                    $message .= var_export($errors->request->getParams(), true);
                }
            }
            $log->log($message, $priority);
        }

        // Conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }

        $this->view->request = $errors->request;
    }

}
